import 'package:animate_do/animate_do.dart';
import 'package:craze/common/index.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:go_router/go_router.dart';
import 'dart:async';
import 'dart:math' as math;

class StartView extends StatefulWidget {
  const StartView({super.key});

  @override
  State<StartView> createState() => _StartViewState();
}

class _StartViewState extends State<StartView> with TickerProviderStateMixin {
  late AnimationController _logoController;
  late AnimationController _textController;
  late Animation<double> _logoScaleAnimation;
  late Animation<double> _logoOpacityAnimation;
  bool _showLogo = false;
  bool _showText = false;
  bool _showParticles = false;
  final math.Random _random = math.Random();
  bool _isNavigating = false;

  @override
  void initState() {
    super.initState();

    // 初始化动画控制器
    _logoController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 1500),
    );

    _textController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 800),
    );

    // 定义动画
    _logoScaleAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _logoController, curve: Curves.elasticOut),
    );

    _logoOpacityAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _logoController,
        curve: const Interval(0.0, 0.5, curve: Curves.easeIn),
      ),
    );

    // 设置动画序列
    Timer(const Duration(milliseconds: 500), () {
      if (mounted) {
        setState(() {
          _showLogo = true;
        });
        _logoController.forward();
      }
    });

    Timer(const Duration(milliseconds: 1500), () {
      if (mounted) {
        setState(() {
          _showText = true;
        });
        _textController.forward();
      }
    });

    Timer(const Duration(milliseconds: 2000), () {
      if (mounted) {
        setState(() {
          _showParticles = true;
        });
      }
    });

    // 设置导航到主页的定时器
    Timer(const Duration(seconds: 4), () {
      if (mounted && !_isNavigating) {
        setState(() {
          _isNavigating = true;
        });
        context.go(AppRouter.home);
      }
    });
  }

  @override
  void dispose() {
    _logoController.dispose();
    _textController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MyImages.startBg),
            fit: BoxFit.cover,
          ),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            if (_showLogo)
              AnimatedBuilder(
                animation: _logoController,
                builder: (context, child) {
                  return Opacity(
                    opacity: _logoOpacityAnimation.value,
                    child: Transform.scale(
                      scale: _logoScaleAnimation.value,
                      child: Image.asset(
                        MyImages.smallLogo,
                        width: 84.w,
                        height: 84.w,
                      ),
                    ),
                  );
                },
              ),
            SizedBox(height: 10.h),
            if (_showText)
              FadeInUp(
                duration: const Duration(milliseconds: 800),
                child: ShaderMask(
                  shaderCallback: (bounds) {
                    return const LinearGradient(
                      colors: [Colors.white, MyColors.blue],
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                    ).createShader(bounds);
                  },
                  child: Text(
                    'Craze',
                    style: GoogleFonts.montserrat(
                      fontSize: 34.sp,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            if (_showParticles) _buildParticleEffect(),
          ],
        ),
      ),
    );
  }

  Widget _buildParticleEffect() {
    return SizedBox(
      height: 120.h,
      width: double.infinity,
      child: Stack(
        children: List.generate(15, (index) {
          // 随机延迟时间
          final delay = (_random.nextInt(10) * 100) % 1500;

          // 随机水平位置，确保左右不规则
          final leftPosition = _random.nextDouble() * 1.sw;

          // 随机大小 (8-16)
          final size = 8 + _random.nextInt(8);

          // 随机旋转角度
          final rotation = _random.nextDouble() * 2 * math.pi;

          // 随机方向 (左或右)
          final isFlipped = _random.nextBool();

          return Positioned(
            left: leftPosition,
            top: _random.nextDouble() * 80.h,
            child: FadeInUp(
              delay: Duration(milliseconds: delay),
              from: 30,
              child: SlideInUp(
                delay: Duration(milliseconds: delay),
                from: 30,
                child: Transform.rotate(
                  angle: rotation,
                  child: Transform.scale(
                    scaleX: isFlipped ? -1.0 : 1.0,
                    child: Icon(
                      MyIcons.iconWater,
                      size: size.sp,
                      color: MyColors.blue.withAlpha(204),
                    ),
                  ),
                ),
              ),
            ),
          );
        }),
      ),
    );
  }
}
